<template>
  <view class="shipping-orders">
    <!-- 加载状态 -->
    <uni-load-more v-if="loading" status="loading"></uni-load-more>
    
    <!-- 无订单提示 -->
    <view v-else-if="!shippingOrders || shippingOrders.length === 0" class="empty-orders">
      <text>暂无待收货订单</text>
      <view class="action-buttons">
        <button type="primary" class="goto-shop" @tap="goToShop">去逛逛</button>
        <button type="default" class="refresh-btn" @tap="fetchShippingOrders">刷新</button>
      </view>
    </view>

    <view v-else class="order-list">
      <view 
        v-for="order in shippingOrders" 
        :key="order.order_no"
        class="order-card animate__animated animate__fadeIn"
      >
        <view class="order-header">
          <text class="order-no">订单号: {{ order.order_no }}</text>
          <text class="order-status">待收货</text>
        </view>
        
        <!-- 物流信息 -->
        <view class="shipping-info" @tap="toggleTracking(order)">
          <view class="info-header">
            <view class="left">
              <text class="bi bi-truck uni-mr-2"></text>
              <text class="status">{{ order.logistics?.status || '运输中' }}</text>
            </view>
            <text class="bi" :class="order.showTracking ? 'bi-chevron-up' : 'bi-chevron-down'"></text>
          </view>
          <text class="track-info">{{ order.logistics?.latest || '正在配送中' }}</text>
          
          <!-- 物流历史记录 -->
          <view 
            v-if="order.showTracking && order.logistics?.history" 
            class="tracking-history animate__animated animate__fadeIn"
          >
            <view 
              v-for="(track, index) in order.logistics.history" 
              :key="index"
              class="track-item"
              :class="{ active: index === 0 }"
            >
              <view class="time-line">
                <view class="dot"></view>
                <view class="line" v-if="index !== order.logistics.history.length - 1"></view>
              </view>
              <view class="track-content">
                <text class="track-time">{{ track.time }}</text>
                <text class="track-desc">{{ track.description }}</text>
              </view>
            </view>
          </view>
        </view>
        
        <view class="order-content">
          <view 
            v-for="item in order.items" 
            :key="item.id"
            class="order-item"
          >
            <image 
              :src="url('sp',item.id-1,'png')" 
              mode="aspectFill"
              class="item-image"
            />
            <view class="item-info">
              <text class="item-name">{{ item.name }}</text>
              <text class="item-spec">{{ formatSpecs(item.specs) }}</text>
              <view class="item-price-qty">
                <text class="price">¥{{ item.price }}</text>
                <text class="quantity">x{{ item.quantity }}</text>
              </view>
            </view>
          </view>
        </view>
        
        <view class="order-footer">
          <view class="total">
            共{{ order.items.length }}件商品
            <text class="total-amount">合计: ¥{{ order.totalAmount }}</text>
          </view>
          <view class="actions">
            <button 
              type="default"
              :class="{ active: order.showTracking }"
              @tap="toggleTracking(order)"
            >
              {{ order.showTracking ? '收起物流' : '查看物流' }}
            </button>
            <button type="warn" @tap="confirmReceived(order)"> <text class="bi bi-check-circle uni-mr-2"></text> 确认收货</button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useUserStore } from '@/stores/userStore'

const url = $url
const userStore = useUserStore()
const loading = ref(true)
const shippingOrders = ref([])

// 格式化规格
const formatSpecs = (specs) => {
  if (!specs) return '';
  return Object.entries(specs).map(([key, value]) => `${key}: ${value}`).join(', ');
};

// 获取待收货订单
const fetchShippingOrders = async () => {
  loading.value = true;
  
  try {
    console.log('开始获取待收货订单...');
    
    // 确保用户已登录
    if (!userStore.isLoggedIn || !userStore.userInfo || !userStore.userInfo.account) {
      console.error('用户未登录，无法获取订单');
      uni.showToast({
        title: '请先登录',
        icon: 'none'
      });
      loading.value = false;
      return;
    }
    
    // 调用云函数获取待收货订单
    const result = await uniCloud.callFunction({
      name: 'orderManage',
      data: {
        body: JSON.stringify({
          action: 'getByStatus',
          account: userStore.userInfo.account,
          status: 'shipping'
        })
      }
    });
    
    if (result.result && result.result.status === 1) {
      // 为每个订单添加showTracking属性
      shippingOrders.value = result.result.data.map(order => ({
        ...order,
        showTracking: false
      }));
    } else {
      throw new Error(result.result?.message || '获取订单失败');
    }
    
  } catch (error) {
    console.error('获取待收货订单失败:', error);
    uni.showToast({
      title: error.message || '获取订单失败',
      icon: 'none'
    });
    shippingOrders.value = [];
  } finally {
    loading.value = false;
  }
};

const toggleTracking = (order) => {
  order.showTracking = !order.showTracking;
};

const confirmReceived = async (order) => {
  uni.showModal({
    title: '确认收货',
    content: '确认已收到商品吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          // 调用云函数更新订单状态
          const result = await uniCloud.callFunction({
            name: 'orderManage',
            data: {
              body: JSON.stringify({
                action: 'update',
                orderId: order._id,
                status: 'review'
              })
            }
          });
          
          if (result.result && result.result.status === 1) {
            uni.showToast({
              title: '已确认收货',
              icon: 'success'
            });
            
            // 刷新订单列表
            fetchShippingOrders();
          } else {
            throw new Error(result.result?.message || '确认收货失败');
          }
        } catch (error) {
          uni.showToast({
            title: '确认收货失败: ' + error.message,
            icon: 'none'
          });
        }
      }
    }
  });
};

// 跳转到商城页面
const goToShop = () => {
  uni.switchTab({
    url: '/pages/shop/index'
  });
};

onMounted(async () => {
  // 检查用户是否登录
  if (!userStore.isLoggedIn) {
    uni.showToast({
      title: '请先登录',
      icon: 'none',
      duration: 2000
    });
    
    setTimeout(() => {
      uni.navigateTo({
        url: '/pages/other/login'
      });
    }, 2000);
    return;
  }
  
  // 加载订单数据
  await fetchShippingOrders();
});
</script>

<style lang="scss" scoped>
.shipping-orders {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding: 20rpx;
}

.empty-orders {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
  margin-top: 30rpx;
  width: 240rpx;
}

.goto-shop, .refresh-btn {
  font-size: 28rpx;
}

.order-card {
  background: #fff;
  border-radius: 20rpx;
  margin-bottom: 20rpx;
  padding: 30rpx;
}

.order-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20rpx;
  font-size: 28rpx;
}

.order-status {
  color: var(--td-warning-color);
}

.shipping-info {
  background: #f8f8f8;
  padding: 20rpx;
  border-radius: 10rpx;
  margin-bottom: 20rpx;
  
  .info-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10rpx;
    
    .left {
      display: flex;
      align-items: center;
    }
  }
}

.track-info {
  font-size: 24rpx;
  color: #666;
}

.tracking-history {
  margin-top: 20rpx;
  padding-top: 20rpx;
  border-top: 1px solid #eee;
}

.track-item {
  display: flex;
  margin-bottom: 20rpx;
  
  &.active {
    .dot {
      background-color: var(--td-brand-color);
    }
    
    .track-time, .track-desc {
      color: var(--td-brand-color);
      font-weight: bold;
    }
  }
}

.time-line {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-right: 20rpx;
  padding-top: 6rpx;
}

.dot {
  width: 20rpx;
  height: 20rpx;
  border-radius: 50%;
  background-color: #999;
}

.line {
  width: 2rpx;
  height: 60rpx;
  background-color: #ddd;
  margin: 4rpx 0;
}

.track-content {
  flex: 1;
}

.track-time {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 8rpx;
}

.track-desc {
  font-size: 26rpx;
  color: #333;
}

.order-item {
  display: flex;
  margin-bottom: 20rpx;
}

.item-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 10rpx;
}

.item-info {
  flex: 1;
  margin-left: 20rpx;
}

.item-name {
  font-size: 28rpx;
  margin-bottom: 10rpx;
}

.item-spec {
  font-size: 24rpx;
  color: #999;
}

.item-price-qty {
  display: flex;
  justify-content: space-between;
  margin-top: 10rpx;
}

.price {
  color: #ff4d4f;
  font-weight: bold;
}

.quantity {
  color: #999;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20rpx;
  padding-top: 20rpx;
  border-top: 2rpx solid #f5f5f5;
}

.total {
  font-size: 28rpx;
  color: #666;
}

.total-amount {
  color: #333;
  font-weight: bold;
  margin-left: 10rpx;
}

.actions {
  display: flex;
  gap: 20rpx;
}

.actions button {
  font-size: 20rpx;


}

button.active {
  background-color: #f0f0f0;
  color: var(--td-brand-color);
}
</style>
